<template>
    <el-dialog title="个人信息" :visible.sync="dialogFormVisible">
        <el-form ref="form" :model="form" :rules="rules">
            <el-form-item prop="avatar" :label-width="formLabelWidth" label="头像">
                    <el-upload
                      class="avatar-uploader"
                      action=""
                      :http-request="uploadImage"
                      :show-file-list="false"
                      :on-success="handleImageSuccess"
                      :before-upload="beforeImageUpload">
                      <img v-if="form.avatar" :src="form.avatar" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入姓名" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="验证码" :label-width="formLabelWidth" prop="emailCode">
              <el-input
                ref="emailCode"
                v-model="form.emailCode"
                type="text"
                placeholder="请输入邮箱验证码"
                name="emailCode"
                tabindex="2"
                autocomplete="on"
                prefix-icon="el-icon-chat-dot-square"
                style="width: 60%; float: left;"
              />
              <el-button
                type="primary"
                plain
                style="float: right"
                :disabled="disabled"
                @click="getEmailCode()"
              >{{btntxt}}</el-button>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import fileApi from "@/api/file";
import {getUserInfo, sendLoginEmail, updateUserForUs} from "@/api/user";
import {v4 as uuidv4} from "uuid";
export default {
    name: 'editUser',
    data() {
        var userEmail = (rule, value, callback) => {
          const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
          if (!value) {
            return callback(new Error("邮箱不能为空"));
          }
          setTimeout(() => {
            if (mailReg.test(value)) {
              callback();
            } else {
              callback(new Error("请输入正确的邮箱格式"));
            }
          }, 100);
        };
        var checkNameLength = (rule, value, callback) => {
          if (!value) {
            return callback(new Error("姓名不能为空"));
          } else {
            return callback();
          }
        };
        //手机验证
        var checkPhone = (rule, value, callback) => {
          const phoneReg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/;
          this.btntxt = "获取验证码";
          this.time = 0;
          if (!value) {
            return callback(new Error("手机号不能为空"));
          }
          if (!Number.isInteger(+value)) {
            return callback(new Error("请输入数字值"));
          }
          if (phoneReg.test(value)) {
            this.time = 60;
            this.btntxt = "获取验证码";
            this.disabled = false;
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        };
        return {
            dialogFormVisible: false,
            loginUUID: '',
            form: {
                nickName: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
                email: '',
                phone: '',
                emailCode: '',
                avatar: ''
            },
            time: 0,
            rules: {
              email: [{validator: userEmail, trigger: "blur"}],
              nickName: [{validator: checkNameLength, trigger: "blur"}],
              phone: [{validator: checkPhone, trigger: "blur"}],
              avatar: [{required: true, message: "头像不能为空", trigger: "blur"}],
              emailCode: [{required: true, message: "验证码不能为空", trigger: "blur"}],
            },
            fileList: [],
            btntxt: "获取验证码",
            disabled: false,
            formLabelWidth: '120px'
        }
    },
    methods: {
        open(){
            this.dialogFormVisible = true
        },
        getEmailCode() {
            this.$refs.form.validateField("email", err => {
                if (!err) {
                    this.time = 60;
                    this.timer();
                    // 向后端请求发送验证码 TODO
                  debugger
                    this.loginUUID = uuidv4()
                    sendLoginEmail(this.form.email, this.loginUUID).then(res => {
                        this.time = 60;
                        this.timer();
                    })
                }
            });
        },
        timer() {
          if (this.time > 0) {
            this.time--;
            this.btntxt = this.time + "s后重新获取";
            this.disabled = true;
            setTimeout(this.timer, 1000);
          } else {
            this.time = 0;
            this.btntxt = "获取验证码";
            this.disabled = false;
          }
        },
        uploadImage(data) {
            let formData = new FormData();
            formData.append('file', data.file);
            fileApi.uploadFile(formData).then(res => {
              this.$message.success("上传成功");
                this.form.avatar = res.data.data;
            });
        },
        handleImageSuccess(res, file) {

        },
        beforeImageUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isGif = file.type === 'image/gif';
            const isPng = file.type === 'image/png';

            if (!isJPG && !isGif && !isPng) {
              this.$message.error('上传头像图片只能是 JPG/GIF/PNG 格式!');
            }
            return isJPG || isGif || isPng;
        },
        submit() {
            this.$refs["form"].validate(valid => {
                if (!valid) return;
                this.form.loginUuid = this.loginUUID;
                updateUserForUs(this.form).then( res => {
                    this.$message.success("操作成功");
                    this.dialogFormVisible = false
                });
            });
        }
    },
    mounted() {
      getUserInfo().then(
        res => {
          this.form = res.data
          console.log(this.form)
        }
      )
    }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
